import { Sequelize } from "sequelize";
import * as path from "path";

// 直接读取 config/database.json
const config = require(path.resolve(
  __dirname,
  "..",
  "config",
  "database.json"
));
const env = process.env.NODE_ENV || "development";
const dbConfig = config[env];

const sequelize = new Sequelize(
  dbConfig.database,
  dbConfig.username,
  dbConfig.password,
  {
    host: dbConfig.host,
    port: dbConfig.port,
    dialect: dbConfig.dialect,
    timezone: dbConfig.timezone,
    define: dbConfig.define,
    logging: console.log,
  }
);

(async () => {
  try {
    // 导入 User 模型
    const DataTypes = require("sequelize").DataTypes;
    const userModel = require(path.resolve(
      __dirname,
      "..",
      "app",
      "model",
      "user.ts"
    ))(sequelize, DataTypes);

    await sequelize.authenticate();
    console.log("Database connected.");

    await sequelize.sync({ alter: true });
    console.log("Database synchronized (alter).");
    process.exit(0);
  } catch (err) {
    console.error(err);
    process.exit(1);
  }
})();
